<?php


namespace app\home\controller;


use app\base\BaseController;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\Exception;
use think\facade\Db;
use think\facade\View;

/**
 * Class Supplier
 * @package app\home\controller
 * 供应商
 */
class Supplier extends BaseController
{
    protected $table='purveyor';
    protected $title='供应商档案';
    private $sessionKey='pageSupplier';
    /**
     * date:2024/3/21
     * 列表
     */
    public function index()
    {
        $param=$this->request->param();
        if (request()->isAjax()) {
            $where[]=['status','>',-1];
            $where[]=['dw_type','=',1];

            $haveAuth=false;
            if ($this->isHaveAuth('see_all')){
                $haveAuth=true;
            }elseif($this->isHaveAuth('see_depart')){
                $haveAuth=true;
                $where[]=['departId','in',$this->dSons];
            }elseif($this->isHaveAuth('see_self')){
                $haveAuth=true;
                $where[]=['createId','=',$this->uid];
            }
            if (!$haveAuth){
                return table_assign(1,'暂无查看权限');
            }

            if (isset($this->param['status'])&&$this->param['status']){
                $where[]=['status','=',$this->param['status']];
            }
            if (isset($this->param['name'])&&$this->param['name']){
                $where[]=['name|contact|phoneNum|code','like','%'.$this->param['name'].'%'];
            }
            session($this->sessionKey,$where);
            $rows = empty($param['limit']) ? get_config('app.page_size') : $param['limit'];
            $list = Db::name($this->table)
                ->where($where)
                ->field('*')
                ->order('id DESC')
                ->paginate($rows);
            return table_assign(0, '', $list);
        } else {
            return view();
        }
    }

    /**
     * @return \json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * date:2024/3/21
     * 添加
     */
    public function add()
    {
        $param = get_params();
        if (request()->isAjax()) {
            $param=$this->param;
            $param['update_time']=time();
            $fdName=$param['name']??'';
            if (!$fdName){
                return to_assign(1,'请输入法定名称');
            }
            $whreCode[]=['deleted','=',0];
            $whreCode[]=['dw_type','=',1];
            $whreCode[]=['name','=',$fdName];
            if ($param['id'] > 0){
                $whreCode[]=['id','<>',$param['id']];
            }
            $haveCode=Db::name($this->table)->where($whreCode)->count();
            if ($haveCode){
                return to_assign(1,'已存在相同的法定名称');
            }
            if ($param['id'] > 0) {
                Db::name($this->table)->strict(false)->field(true)->update($param);
                add_log('edit', $param['id'], $param,$this->title);
            } else {
                $param['createId']=$this->uid;
                $param['departId']=$this->did;
                $param['dw_type']=1;
                $param['create_time'] = time();
                $rid = Db::name($this->table)->strict(false)->field(true)->insertGetId($param);
                add_log('add', $rid, $param,$this->title);
            }
            return to_assign();
        } else {
            $id = isset($param['id']) ? $param['id'] : 0;
            if ($id > 0) {
                $detail = Db::name($this->table)->where('id', $id)->find();
                View::assign('detail', $detail);
            }
//            $adminList=Db::name('admin')->where('id','>',1)->where('status',1)->field('id,name')->select();
//            View::assign('adminList', $adminList);
            View::assign('id', $id);
            return view('form');
        }
    }

    /**
     * @return \json
     * @throws \think\db\exception\DbException
     * date:2024/3/21
     * 删除
     */
    public function delete()
    {
        if (request()->isDelete()) {
            $id = get_params("id");
            try {
                Db::name($this->table)->where('id','in',$id)->update(['status'=>-1,'deleted'=>time()]);
                Db::name('purveyor_member')->where('purveyorId','in',$id)->update(['status'=>-1,'deleted'=>time()]);
                add_log('delete', $id, request()->param(),$this->title);
            }catch (\Exception $e){
                return to_assign(1, "删除失败".$e->getMessage());
            }
            return to_assign(0, "删除成功");
        } else {
            return to_assign(1, "错误的请求");
        }
    }

    /**
     * @return \json
     * @throws \think\db\exception\DbException
     * date:2024/4/1
     * 启用/禁用
     */
    public function doCheck()
    {
        $param = get_params();
        $param['update_time']=time();
        $res = Db::name($this->table)->strict(false)->field('id,status,update_time')->update($param);
        if ($res) {
            if($param['status'] == 2){
                add_log('disable', $param['id'], $param,$this->title);
            }
            else if($param['status'] == 1){
                add_log('recovery', $param['id'], $param,$this->title);
            }
            return to_assign();
        }
        else{
            return to_assign(0, '操作失败');
        }
    }

    public function importData()
    {
        Db::startTrans();
        try {
            if (!isset($_FILES['file'])){
                throw new Exception('请选择上传文件');
            }
            //限制上传表格类型
            $fileExtendName = substr(strrchr($_FILES['file']["name"], '.'), 1);
            //application/vnd.ms-excel  为xls文件类型
            if ($fileExtendName != 'xlsx') {
                throw new Exception('必须为excel表格，且必须为xlsx格式！');
            }

            if (is_uploaded_file($_FILES['file']['tmp_name'])) {
                // 有Xls和Xlsx格式两种
//            $objReader = \IOFactory::createReader('Xlsx');
                $objReader = IOFactory::createReader('Xlsx');

                $filename = $_FILES['file']['tmp_name'];

                $objPHPExcel = $objReader->setReadDataOnly(true)->load($filename);  //$filename可以是上传的表格，或者是指定的表格

                $sheet = $objPHPExcel->getSheet(0);   //excel中的第一张sheet
                $highestRow = $sheet->getHighestRow();       // 取得总行数
                $importData = [];
                $names=[];
                $codes=[];
                $registAdds=[];
                $phoneNums=[];
                $bankCards=[];
                $banks=[];
//                $bankNames=[];
                $contarcts=[];
                $contarctAdds=[];
                $contarctPhones=[];
                //循环读取excel表格，整合成数组。如果是不指定key的二维，就用$data[i][j]表示。
                for ($j = 2; $j <= $highestRow; $j++) {

                    $name=$objPHPExcel->getActiveSheet()->getCell("A" . $j)->getFormattedValue();
//                    $fdName=$objPHPExcel->getActiveSheet()->getCell("B" . $j)->getFormattedValue();
                    $code=$objPHPExcel->getActiveSheet()->getCell("B" . $j)->getFormattedValue();
                    $registAdd=$objPHPExcel->getActiveSheet()->getCell("C" . $j)->getFormattedValue();
                    $phoneNum=$objPHPExcel->getActiveSheet()->getCell("D" . $j)->getFormattedValue();
                    $bank=$objPHPExcel->getActiveSheet()->getCell("E" . $j)->getFormattedValue();
//                    $bankName=$objPHPExcel->getActiveSheet()->getCell("F" . $j)->getFormattedValue();
                    $bankCard=$objPHPExcel->getActiveSheet()->getCell("F" . $j)->getFormattedValue();
                    $contarct=$objPHPExcel->getActiveSheet()->getCell("G" . $j)->getFormattedValue();
                    $contarctAdd=$objPHPExcel->getActiveSheet()->getCell("H" . $j)->getFormattedValue();
                    $contarctPhone=$objPHPExcel->getActiveSheet()->getCell("I" . $j)->getFormattedValue();
//
//                    if ($name){
////                        $has=Db::name($this->table)
////                            ->where('status','>',-1)
////                            ->where('dw_type','=',1)
////                            ->where('name',$name)->count();
////                        if ($has){
////                            throw new Exception($j-1 .'行已存在相同的名称');
////                        }
//                    }
                    if ($name){
                        $names[]=$name;
                        $codes[]= $code;
                        $registAdds[]=$registAdd;
                        $phoneNums[]= $phoneNum;
                        $banks[]= $bank;
//                        $bankNames[]=$bankName;
                        $bankCards[]=$bankCard;
                        $contarcts[]=$contarct;
                        $contarctAdds[]=$contarctAdd;
                        $contarctPhones[]=$contarctPhone;

                    }

                }
                $res=$this->createImportData($names,$codes,$registAdds,
                    $phoneNums,$banks,$bankCards,$contarcts,$contarctAdds
                    ,$contarctPhones);
                if ($res['code']!=1){
                    throw new Exception($res['msg']);
                }
                $data=$res['data'];
                foreach ($data as $v){
                    $inszhu=$v['zhu'];
                    $inszi=$v['zi'];
                    $pId=Db::name($this->table)->insertGetId($inszhu);
                    foreach ($inszi as $ky=>&$z){
                        $z['purveyorId']=$pId;
                        $z['createId']=$this->uid;
                        $z['departId']=$this->did;
                        $z['create_time']=time();
                        $z['update_time']=time();
                    }
                    Db::name('purveyor_member')->insertAll($inszi);
                }
                if ($data){
                    Db::name($this->table)->insertAll($importData);
                    add_log('import', '', $data,$this->title);
                }

            }
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            return to_assign(1,'操作失败:'.$e->getMessage());
        }
        return to_assign();

    }
    public function createImportData($names,$codes,$registAdds,$phoneNums,$banks,$bankCards,$contarcts,$contarctAdds,$contarctPhones)
    {
        $uniName=array_unique($names);
        $zhudata=[];
        $ziContract=[];
        $ziSave=[];
        foreach ($names as $k=>$v){
            if (!isset($zhudata[$v])){
                $zhudata[$v]=[
                    "name" => $names[$k],
                    "code" => $codes[$k],
                    "registAdd" => $registAdds[$k],
                    "phoneNum" => $phoneNums[$k],
                    "bank" => $banks[$k],
//                    "bankName" => $bankNames[$k],
                    "bankCard" => $bankCards[$k],
                    "deleted" =>0,
                    "dw_type" =>1,
                    "createId" =>$this->uid,
                    "departId" =>$this->did,
                    "create_time"=>time(),
                    'update_time'=>time()
                ];
            }
            $ziContract[$v][]=[
                'name'=>$contarcts[$k],
                'phone'=>$contarctPhones[$k],
                'address'=>$contarctAdds[$k],
//                'addType'=>$saveAddTypes[$k],
                'type'=>1
            ];
//            $ziSave[$v][]=[
//                'name'=>$saveUsers[$k],
//                'phone'=>$savePhones[$k],
//                'address'=>$saveAdds[$k],
//                'addType'=>$saveAddTypes[$k],
//                'type'=>2
//            ];
        }
        $pData=[];
        foreach ($uniName as $u){
        $has=Db::name($this->table)
         ->where('status','>',-1)
          ->where('dw_type','=',1)
          ->where('name',$u)->count();
           if ($has){
               return ['code'=>0,'msg'=>'已存在相同的名称','data'=>[]];
       }
            $zu=$zhudata[$u];
            $cn=$ziContract[$u];
//            $sa=$ziSave[$u];
//            $zi=array_merge($cn,$sa);
            $pData[]=[
                'zhu'=>$zu,
                'zi'=>$cn
            ];

        }
        return['code'=>1,'msg'=>'','data'=>$pData];
    }

    public function exportData()
    {
        $where=session($this->sessionKey);
        $list = Db::name($this->table)
            ->where($where)
            ->field('*')
            ->order('id DESC')->select()->each(function ($item){
                $item['status']=$item['status']==1?'启用':'禁用';
                return $item;
            });
        $title = [
            'id' => 'ID',
            'name' => '供应商名称',
            'gz_day' => '挂账日',
            'contact' => '联系人',
            'phoneNum' => '手机号',
            'status' => '状态',
        ];
        $name =$this->title;
        exportXlsData($name,$title,$list);
        exit();
    }

    public function info()
    {
        $param=$this->param;
        $id = isset($param['id']) ? $param['id'] : 0;
        $detail = Db::name($this->table)->where('id', $id)->find();
        View::assign('detail', $detail);
        $adminList=Db::name('admin')->where('id','>',1)->where('status',1)->field('id,name')->select();
        View::assign('adminList', $adminList);
        View::assign('id', $id);
        $contactList=Db::name('purveyor_member')
            ->where('purveyorId',$id)->where('type',1)->where('status',1)
            ->select();
        view::assign('contactList',$contactList);
        $receiverList=Db::name('purveyor_member')
            ->where('purveyorId',$id)->where('type',2)->where('status',1)
            ->select();
        view::assign('receiverList',$receiverList);
        return view();
    }

    public function contactAdd()
    {
        $punterId=$this->param['punterId']??'';
        $id=$this->param['id']??'';
        if ($this->request->isAjax()){
            $data=$this->param;
            $data['createId']=$this->uid;
            $data['type']=1;
            $data['departId']=$this->did;
            $data['create_time']=time();
            $data['update_time']=time();
            try {
                if ($id){
                    unset($data['departId']);
                    unset($data['createId']);
//                    unset($data['punterId']);
                    unset($data['create_time']);
                    Db::name('purveyor_member')->where('id',$id)->update($data);
                    add_log('edit', $id, request()->param(),$this->title.' 联系人');
                }else{
                    $id=Db::name('purveyor_member')->insert($data);
                    add_log('add', $id, request()->param(),$this->title.' 联系人');
                }

            }catch (\Exception $e){
                return to_assign(1,'操作失败:'.$e->getMessage());
            }
            return to_assign();
        }else{
            $info=[];
            if ($id){
                $info=Db::name('purveyor_member')->where('id',$id)->find();
            }
            view::assign('detail',$info);
            view::assign('punterId',$punterId);
            view::assign('type',1);
            return view('contactForm');
        }
    }

    public function removeContact()
    {
        $id=$this->param['id'];
        if (!$id){
            return to_assign(1,'参数缺失');
        }
        try {
            Db::name('purveyor_member')->where('type',1)->where('id',$id)->update(['status'=>-1,'deleted'=>time()]);
            add_log('delete', $id, request()->param(),$this->title.' 联系人');
        }catch (\Exception $e){
            return to_assign(1,'操作失败:'.$e->getMessage());
        }
        return to_assign();
    }
//    public function receiverAdd()
//    {
//        $punterId=$this->param['punterId']??'';
//        if ($this->request->isAjax()){
//            $data=$this->param;
//            $data['createId']=$this->uid;
//            $data['type']=2;
//            $data['departId']=$this->did;
//            $data['create_time']=time();
//            $data['update_time']=time();
//            try {
//                $id=Db::name('purveyor_member')->insert($data);
//                add_log('add', $id, request()->param(),$this->title.' 联系人');
//            }catch (\Exception $e){
//                return to_assign(1,'操作失败:'.$e->getMessage());
//            }
//            return to_assign();
//        }else{
//
//            view::assign('punterId',$punterId);
//            view::assign('type',2);
//            return view('contactForm');
//        }
//    }
//
//    public function removeReceiver()
//    {
//        $id=$this->param['id'];
//        if (!$id){
//            return to_assign(1,'参数缺失');
//        }
//        try {
//            Db::name('purveyor_member')->where('type',2)->where('id',$id)->update(['status'=>-1,'deleted'=>time()]);
//            add_log('delete', $id, request()->param(),$this->title.' 联系人');
//        }catch (\Exception $e){
//            return to_assign(1,'操作失败:'.$e->getMessage());
//        }
//        return to_assign();
//    }
}